package com.vincce.fitness.core.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * Created by longlong on 14-8-25.
 */
public class WebInitializer implements WebApplicationInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		WebApplicationContext webContext = getAnnotationContext();
		servletContext.addListener(new ContextLoaderListener(webContext));

		FilterRegistration.Dynamic charEncodingFilter = servletContext.addFilter("CharacterEncodingFilter", CharacterEncodingFilter.class);
		charEncodingFilter.setInitParameter("encoding","UTF-8");
		charEncodingFilter.setInitParameter("forceEncoding","true");
		charEncodingFilter.addMappingForUrlPatterns(null, false, "/*");

		FilterRegistration.Dynamic shiroFilter = servletContext.addFilter("shiroFilter", new DelegatingFilterProxy());
		shiroFilter.setInitParameter("targetFilterLifecycle","true");
		shiroFilter.addMappingForUrlPatterns(null,false,"*.htm");

		DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
		ServletRegistration.Dynamic dispatcher = servletContext.addServlet("appServlet", dispatcherServlet);
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("*.html","*.htm","*.json","*.api");
	}

	private AnnotationConfigWebApplicationContext getAnnotationContext(){
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.setConfigLocation("com.vincce.fitness.core.config");
		context.getEnvironment().setActiveProfiles("production");
		return context;
	}
}
